package org.mobiletrain.android43_activeandroid;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import java.util.Collection;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

public class MyListViewAdapter extends BaseAdapter {
    private List<Student> list = null;
    private LayoutInflater inflater = null;

    public MyListViewAdapter(Context context, List<Student> list) {
        this.list = list;
        inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        ViewHolder mHolder=null;
        if (convertView == null) {
            convertView = inflater.inflate(R.layout.item_listview_main, parent, false);
            mHolder = new ViewHolder(convertView);

            convertView.setTag(mHolder);
        } else {
            mHolder = (ViewHolder) convertView.getTag();
        }
        mHolder.textView_item_name.setText(list.get(position).getName());
        mHolder.textView_item_sex.setText(list.get(position).getSex());
        mHolder.textView_item_age.setText(list.get(position).getAge() + "");
        mHolder.textView_item_id.setText(list.get(position).getId() + "");
        mHolder.textView_item_grade.setText(list.get(position).getGrade());

        return convertView;
    }


    static class ViewHolder {
        @Bind(R.id.textView_item_name)
        TextView textView_item_name;
        @Bind(R.id.textView_item_sex)
        TextView textView_item_sex;
        @Bind(R.id.textView_item_age)
        TextView textView_item_age;
        @Bind(R.id.textView_item_id)
        TextView textView_item_id;
        @Bind(R.id.textView_item_grade)
        TextView textView_item_grade;
        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }


    // 重新加载Listview
    public void reloadListView(Collection<? extends Student> collection, boolean isClear) {
        if (isClear) {
            list.clear();
        }
        list.addAll(collection);
        notifyDataSetChanged();
    }
}
